﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace HttpUploader5.demoDistributed.db
{
	public partial class ajax_post : System.Web.UI.Page
	{
		/// <summary>
		/// 只负责拼接文件块。
		/// 由控件上传远程文件路径。此文件不会从数据库中读取远程文件路径。
		/// 远程文件路径一般在 ajax_create_fid.aspx 中返回。
		/// 
		/// 更新记录：
		///		2012-04-12 更新文件大小变量类型，增加对2G以上文件的支持。
		///		2012-04-18 取消更新文件上传进度信息逻辑。
		///		2012-06-27 取消数据库读取操作。
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void Page_Load(object sender, EventArgs e)
		{
			string struid = Request.Form["uid"];
			string strfid = Request.Form["fid"];
			string md5 = Request.Form["md5"];
			string strFileSize = Request.Form["FileSize"];
			string strRangePos = Request.Form["RangePos"];
			string pathRemote = Request.Form["PathRemote"];//远程文件路径
			string complete = Request.Form["complete"];//truee/false

			//参数为空
			if (strFileSize == null
				|| struid == null
				|| strfid == null
				|| md5 == null
				|| strRangePos == null
				|| pathRemote == null)
			{
				XDebug.Output("fileSize", strFileSize);
				XDebug.Output("uid", struid);
				XDebug.Output("fid", strfid);
				XDebug.Output("md5", md5);
				XDebug.Output("pathRemote", pathRemote);
				XDebug.Output("param is null");
				return;
			}

			if (strFileSize.Length > 0
				&& struid.Length > 0
				&& strfid.Length > 0
				&& md5.Length > 0
				&& strRangePos.Length > 0
				&& Request.Files.Count > 0)
			{
				pathRemote = HttpUtility.UrlDecode(pathRemote);//客户端进行了URL编码
				long fileSize = Convert.ToInt64(strFileSize);
				long rangePos = Convert.ToInt64(strRangePos);
				int uid = Convert.ToInt32(struid);
				int fid = Convert.ToInt32(strfid);

				//临时文件大小
				HttpPostedFile file = Request.Files.Get(0);
				long rangeSize = file.InputStream.Length;

				//xdb_files inf = new xdb_files();
				//HttpUploaderDB db = new HttpUploaderDB();

				//if (db.GetFileInfByFid(fid, ref inf))
				{
					//已上传大小 = 文件块索引 + 临时文件块大小
					long postedLength = rangePos + rangeSize;
					//上传百分比 = 已上传大小 / 文件总大小
					double per = ((double)postedLength / (double)fileSize) * 100;
					decimal perd = Math.Round((decimal)per,2);
					string postedPercent = perd.ToString() + "%";

					XDebug.Output("per", per);
					XDebug.Output("fileSize", fileSize);
					XDebug.Output("postedPercent", postedPercent);
					XDebug.Output("uid", struid);
					XDebug.Output("fid", strfid);
					XDebug.Output("rangePos", rangePos);
					XDebug.Output("postedLength", postedLength);
					XDebug.Output("postedPercent", postedPercent);

					//保存文件块数据
					FileResumer res = new FileResumer();
					res.m_FileSize = fileSize;
					res.RangePos = rangePos;
					res.Resumer(ref file, pathRemote);
				}
				Response.Write("ok");
			}
		}
	}
}
